package org.dxy.domain.handler.workstation;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IWorkstationRepository;
import org.dxy.domain.command.workstation.CreateWorkstationCommand;
import org.dxy.domain.model.aggregate.Workstation;
import org.dxy.types.common.CommandResult;
import org.dxy.types.id.HutoolSnowflakeGenerator;
import org.springframework.stereotype.Component;

/**
 * @description: 处理创建工位命令的处理器
 * @author: dxy
 * @createTime: 2025/6/18 22:36
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CreateWorkstationCommandHandler implements CommandHandler<CreateWorkstationCommand, Long> {

    private final IWorkstationRepository workstationRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Long> handle(CreateWorkstationCommand command) {
        try {
            long workstationId = HutoolSnowflakeGenerator.generateId();
            Workstation workstation = Workstation.create(command, workstationId);
            workstationRepository.save(workstation);
            workstation.getDomainEvents().forEach(eventBus::post);
            workstation.clearDomainEvents();
            
            log.info("工位创建成功, command={}", command);
            return CommandResult.success(workstationId, "工位创建成功");
        } catch (IllegalStateException e) {
            log.warn("工位创建失败，原因：{}", e.getMessage());
            return CommandResult.fail(null,e.getMessage());
        }
    }
}
